<template>
	<view class="bi-company-select" :class="['is-align-' + align]" @click="handleClick">
		<view v-if="innerValue" class="bi-company-select__value">{{ showText }}</view>
		<view v-else class="bi-company-select__placeholder">选择公司</view>
	</view>
</template>

<script>
	import { buildUrl } from '@/utils/url'
	import { unique } from '@/utils/string'
	import Event from '@/utils/event.js'
	
	export default {
		name: 'BiCompanySelect',
		props: {
			value: {
				type: String
			},
			text: {
				type: String
			},
			align: {
				type: String,
				default: 'left'
			}
		},
		computed: {
			innerValue: {
				get () {
					return this.value
				},
				set (val) {
					this.$emit('input', val)
				}
			},
			showText () {
				if (!this.innerValue) {
					return
				}
				return this.text || this.innerValue
			}
		},
		created () {
			this.id = unique('company_select_')
			Event.on(this.id, ({ setCallback }) => {
				setCallback(({ selection }) => {
					return new Promise((resolve, reject) => {
						let isTry = false
						const doChange = () => {
							if (selection && selection.length) {
								this.innerValue = selection[0].id
								this.$emit('change', {
									item: selection[0]
								})
							} else {
								this.innerValue = ''
								this.$emit('change', {
									item: null
								})
							}
							resolve()
						}
						this.$emit('confirm', {
							setCallback: (fn) => {
								isTry = true
								if (fn) {
									const rs = fn({
										selection
									})
									if (rs && rs.then) {
										rs.then(() => {
											doChange()
										}, reject)
									} else {
										doChange()
									}
								} else {
									doChange()
								}
							}
						})
						if (!isTry) {
							doChange()
						}
					})
					
				})
			})
		},
		methods: {
			handleClick () {
				const params = {
					eventName: this.id,
					multiple: false
				}
				if (this.innerValue) {
					params.value = this.innerValue
				}
				uni.navigateTo({
					url: buildUrl('/packages/common/company-select/company-select', params)
				})
			}
		},
		beforeDestroy () {
			Event.off(this.id)
		}
	}
</script>

<style lang="less">
	.bi-company-select{
		&.is-align-right {
			text-align: right;
		}
	}
	.bi-company-select__value{
		line-height: 24px;
		padding: 8px 0;
	}
	.bi-company-select__placeholder{
		line-height: 24px;
		padding: 8px 0;
		color: #808080;
	}
</style>